﻿using KBWebApi.Common;
using KBWebApi.Model;
using SqlSugar;
using System;
using System.Data;

namespace KBWebApi.Dal
{
    public class KBDal
    {
        private static SqlSugarScope db = SqlDBHelper.SqlHelper.GetDB();

        public static bool IsExists(KBInputModel inputModel)
        {
            try
            {
                bool isexists = db.Queryable<KBInputModel>().Any(t => t.XS_KanBanId == inputModel.XS_KanBanId);
                return isexists;
            }
            catch (Exception ex)
            {
                WriteLog.Writelog("KB.IsExists=>" + ex.ToString());
                return false;
            }
        }

        public int NewKBInput(KBInputModel inputModel)
        {
            int count = db.Insertable(inputModel).ExecuteCommand();
            return count;
        }

        public int Update(KBInputModel inputModel)
        {
            int count = db.Updateable(inputModel).IgnoreColumns(t => new { t.CreateDate }).ExecuteCommand();
            return count;
        }

        public int Delete(string KBId)
        {
            int count = db.Deleteable<KBInputModel>().Where(t => t.XS_KanBanId == int.Parse(KBId)).ExecuteCommand();
            return count;
        }

        public static DataTable GetList(string name)
        {
            string sql = $@"SELECT {name} FROM XS_{name} WHERE {name} IS NOT NULL";
            return db.SqlQueryable<DataTable>(sql).ToDataTable();
        }

        public static DataTable GetAllList(KBInputModel inputModel)
        {
            return db.Queryable<KBInputModel>()
            .WhereIF(inputModel != null && !string.IsNullOrEmpty(inputModel.WorkShop), t => t.WorkShop == inputModel.WorkShop)
            .WhereIF(inputModel != null && !string.IsNullOrEmpty(inputModel.WorkStation), t => t.WorkStation == inputModel.WorkStation)
            .WhereIF(inputModel != null && !string.IsNullOrEmpty(inputModel.ProductNo), t => t.ProductNo.Contains(inputModel.ProductNo))
            .WhereIF(inputModel != null && !string.IsNullOrEmpty(inputModel.ProductDesc), t => t.ProductDesc.Contains(inputModel.ProductDesc))
            .WhereIF(inputModel != null && !string.IsNullOrEmpty(inputModel.WorkStatus), t => t.WorkStatus == inputModel.WorkStatus)
            .WhereIF(inputModel != null && inputModel.ProduceDate != DateTime.MinValue, t => SqlFunc.DateIsSame(t.ProduceDate, inputModel.ProduceDate))
            .With(SqlWith.NoLock)
            .OrderBy(t => new { t.XS_KanBanId, t.ProduceDate })
            .ToDataTable();
        }
    }
}
